package com.eduagent.xwqeduagent.api.CreativePosterGeneration.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.eduagent.xwqeduagent.api.CreativePosterGeneration.model.CreatePosterTaskRequest;
import com.eduagent.xwqeduagent.api.CreativePosterGeneration.model.CreatePosterTaskResponse;
import com.eduagent.xwqeduagent.api.CreativePosterGeneration.model.GetPosterTaskResponse;
import com.eduagent.xwqeduagent.exception.BusinessException;
import com.eduagent.xwqeduagent.exception.ErrorCode;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 创意海报生成API
 */
@Slf4j
@Component
public class CreativePosterGenerationApi {
    // 读取配置文件中的API Key
    @Value("${aliYunAi.apiKey}")
    private String apiKey;
    
    // 使用Jackson的ObjectMapper来处理JSON序列化
    private final ObjectMapper objectMapper;
    
    // 构造函数初始化ObjectMapper
    public CreativePosterGenerationApi() {
        this.objectMapper = new ObjectMapper();
        // 配置ObjectMapper忽略未知属性
        this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    // 创建任务地址
    public static final String CREATE_POSTER_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis";

    // 查询任务状态地址
    public static final String GET_POSTER_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 创建创意海报生成任务
     * @param request 请求参数
     * @return 创建任务的响应
     */
    public CreatePosterTaskResponse createPosterTask(CreatePosterTaskRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        
        // 参数验证
        if (request.getInput() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "输入参数不能为空");
        }
        
        if (StrUtil.isBlank(request.getInput().getTitle())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "主标题不能为空");
        }
        
        if (StrUtil.isBlank(request.getInput().getPromptTextZh()) && StrUtil.isBlank(request.getInput().getPromptTextEn())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "中文提示词和英文提示词至少需要设置一个");
        }
        
        // 详细记录请求内容
        log.info("创意海报生成请求参数详情: model={}, title={}, generateMode={}",
                request.getModel(),
                request.getInput().getTitle(),
                request.getInput().getGenerateMode());

        try {
            // 使用Jackson序列化，它会尊重@JsonProperty注解
            String requestBody = objectMapper.writeValueAsString(request);
            
            // 发送请求
            HttpRequest httpRequest = HttpRequest.post(CREATE_POSTER_TASK_URL)
                    .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                    // 必须开启异步处理，设置为enable
                    .header("X-DashScope-Async", "enable")
                    .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                    .body(requestBody);
            
            try (HttpResponse httpResponse = httpRequest.execute()) {
                if (!httpResponse.isOk()) {
                    log.error("请求异常：{}", httpResponse.body());
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "创意海报生成请求失败");
                }
                
                CreatePosterTaskResponse response = objectMapper.readValue(httpResponse.body(), CreatePosterTaskResponse.class);
                String errorCode = response.getCode();
                if (StrUtil.isNotBlank(errorCode)) {
                    String errorMessage = response.getMessage();
                    log.error("创意海报生成失败，errorCode:{}, errorMessage:{}", errorCode, errorMessage);
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "创意海报生成接口响应异常");
                }
                
                return response;
            }
        } catch (Exception e) {
            log.error("创意海报生成任务创建异常", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创意海报生成任务创建异常: " + e.getMessage());
        }
    }

    /**
     * 查询创意海报生成任务
     * @param taskId 任务ID
     * @return 任务查询结果
     */
    public GetPosterTaskResponse getPosterTask(String taskId) {
        if (StrUtil.isBlank(taskId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        }
        
        try {
            HttpResponse httpResponse = HttpRequest.get(String.format(GET_POSTER_TASK_URL, taskId))
                    .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                    .execute();
                    
            if (!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取创意海报生成任务失败");
            }
            
            return objectMapper.readValue(httpResponse.body(), GetPosterTaskResponse.class);
        } catch (Exception e) {
            log.error("获取创意海报生成任务异常", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取创意海报生成任务异常: " + e.getMessage());
        }
    }
} 